// ... existing code ...
<script setup>
import { ref, onMounted } from 'vue'
import { ElTable, ElTableColumn, ElPagination, ElInput, ElButton, ElIcon, ElDialog, ElSelect, ElOption, ElMessage, ElForm, ElFormItem, ElMessageBox } from 'element-plus'
import { Search, Edit, Plus, Delete } from '@element-plus/icons-vue'
import academyApi from '../../../api/academy.js'

// 编辑学院专业弹窗相关
const editDialogVisible = ref(false)
const editingAcademy = ref(null)
const academyMajors = ref([])
const editDialogLoading = ref(false)
// 定义表格数据
const academyData = ref([])
// 分页数据
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 搜索关键词
const searchKeyword = ref('')
// 加载状态
const loading = ref(false)

// 弹窗相关
const dialogVisible = ref(false)
const selectedAcademyId = ref(null)
const selectedMajorId = ref(null)
const majorList = ref([])
const dialogLoading = ref(false)

// 新增学院相关
const addDialogVisible = ref(false)
const newAcademyName = ref('')
const addDialogLoading = ref(false)
const addForm = ref({
  model: {
    academyName: ''
  },
  rules: {
    academyName: [
      { required: true, message: '请输入学院名称', trigger: 'blur' },
      { min: 1, max: 50, message: '学院名称长度在 1 到 50 个字符', trigger: 'blur' }
    ]
  }
})

// 获取学院分页数据
const getAcademyData = async (pageNum = 1, pageSize = 10, academyName = '') => {
  loading.value = true
  try {
    const response = await academyApi.getAcademyPage(pageNum, pageSize, academyName)

    // 处理返回的数据
    if (response && response.code === 200) {
      // 正确处理MyBatis-Plus的Page对象
      academyData.value = response.data.records || []
      pagination.value.total = response.data.total || 0
    } else {
      console.error('获取学院数据失败:', response?.msg || '未知错误')
    }
  } catch (error) {
    console.error('请求学院数据时发生错误:', error)
  } finally {
    loading.value = false
  }
}

// 分页变化时触发
const handleCurrentChange = (currentPage) => {
  pagination.value.currentPage = currentPage
  getAcademyData(currentPage, pagination.value.pageSize, searchKeyword.value)
}

// 每页条数变化时触发
const handleSizeChange = (pageSize) => {
  pagination.value.pageSize = pageSize
  getAcademyData(pagination.value.currentPage, pageSize, searchKeyword.value)
}

// 搜索学院
const handleSearch = () => {
  pagination.value.currentPage = 1
  getAcademyData(1, pagination.value.pageSize, searchKeyword.value)
}

// 打开编辑弹窗
const openEditDialog = async (academy) => {
  selectedAcademyId.value = academy.id
  selectedMajorId.value = null
  dialogVisible.value = true

  try {
    dialogLoading.value = true
    const response = await academyApi.getMajorList()
    if (response && response.code === 200) {
      majorList.value = response.data || []
    } else {
      ElMessage.error('获取专业列表失败: ' + (response?.msg || '未知错误'))
    }
  } catch (error) {
    console.error('请求专业列表时发生错误:', error)
    ElMessage.error('获取专业列表失败')
  } finally {
    dialogLoading.value = false
  }
}

// 提交关联
const submitJoin = async () => {
  if (!selectedMajorId.value) {
    ElMessage.warning('请选择专业')
    return
  }

  try {
    dialogLoading.value = true
    const response = await academyApi.joinMajorToAcademy(selectedAcademyId.value, selectedMajorId.value)

    if (response && response.code === 200) {
      ElMessage.success('专业关联成功')
      dialogVisible.value = false
    } else {
      ElMessage.error('专业关联失败: ' + (response?.msg || '未知错误'))
    }
  } catch (error) {
    console.error('提交专业关联时发生错误:', error)
    ElMessage.error('专业关联失败')
  } finally {
    dialogLoading.value = false
  }
}

// 打开新增学院弹窗
const openAddDialog = () => {
  addDialogVisible.value = true
  addForm.value.model.academyName = ''
}

// 提交新增学院
const submitAddAcademy = async () => {
  try {
    addDialogLoading.value = true
    const response = await academyApi.createAcademy(addForm.value.model.academyName)

    if (response && response.code === 200) {
      ElMessage.success('学院创建成功')
      addDialogVisible.value = false
      // 重新加载学院列表
      getAcademyData(pagination.value.currentPage, pagination.value.pageSize, searchKeyword.value)
    } else {
      ElMessage.error('学院创建失败: ' + (response?.msg || '未知错误'))
    }
  } catch (error) {
    console.error('创建学院时发生错误:', error)
    ElMessage.error('学院创建失败')
  } finally {
    addDialogLoading.value = false
  }
}

// 打开编辑学院专业弹窗
const openEditMajorsDialog = async (academy) => {
  editingAcademy.value = academy
  editDialogVisible.value = true

  try {
    editDialogLoading.value = true
    const response = await academyApi.getAcademyMajors(academy.id)
    if (response && response.code === 200) {
      academyMajors.value = response.data || []
    } else {
      ElMessage.error('获取学院专业列表失败: ' + (response?.msg || '未知错误'))
    }
  } catch (error) {
    console.error('请求学院专业列表时发生错误:', error)
    ElMessage.error('获取学院专业列表失败')
  } finally {
    editDialogLoading.value = false
  }
}

// 删除学院关联的专业
const deleteMajor = async (majorId) => {
  if (!editingAcademy.value) return

  try {
    editDialogLoading.value = true
    const response = await academyApi.deleteAcademyMajor(editingAcademy.value.id, majorId)

    if (response && response.code === 200) {
      ElMessage.success('专业删除成功')
      // 重新加载学院专业列表
      const refreshResponse = await academyApi.getAcademyMajors(editingAcademy.value.id)
      if (refreshResponse && refreshResponse.code === 200) {
        academyMajors.value = refreshResponse.data || []
      }
    } else {
      ElMessage.error('专业删除失败: ' + (response?.msg || '未知错误'))
    }
  } catch (error) {
    console.error('删除专业时发生错误:', error)
    ElMessage.error('专业删除失败')
  } finally {
    editDialogLoading.value = false
  }
}
// 删除学院
const deleteAcademy = async (academyId, academyName) => {
  try {
    // 弹出确认对话框
    await ElMessageBox.confirm(
        `确定要删除学院 "${academyName}" 吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const response = await academyApi.deleteAcademy(academyId)

    if (response && response.code === 200) {
      ElMessage.success('学院删除成功')
      // 重新加载学院列表
      getAcademyData(pagination.value.currentPage, pagination.value.pageSize, searchKeyword.value)
    } else {
      ElMessage.error('学院删除失败: ' + (response?.msg || '未知错误'))
    }
  } catch (error) {
    // 用户取消删除操作时不会显示错误信息
    if (error !== 'cancel') {
      console.error('删除学院时发生错误:', error)
      ElMessage.error('学院删除失败')
    }
  }
}
// 初始加载数据
onMounted(() => {
  getAcademyData()
})
</script>

<template>
  <div class="college-container">
    <div class="search-bar">
      <ElInput
          v-model="searchKeyword"
          placeholder="请输入学院名称"
          class="search-input"
          :prefix-icon="Search"
      />
      <ElButton type="primary" @click="handleSearch">搜索</ElButton>
      <ElButton type="primary" @click="openAddDialog" :icon="Plus" style="margin-left: 10px">
        新增学院
      </ElButton>
    </div>

    <ElTable
        :data="academyData"
        style="width: 100%"
        v-loading="loading"
        element-loading-text="加载中..."
    >
      <ElTableColumn prop="academyName" label="学院名称" width="400" />
      <ElTableColumn label="操作" width="400" fixed="right">
        <template #default="scope">
          <ElButton
              type="primary"
              size="small"
              @click="openEditDialog(scope.row)"
              :icon="Plus"
              style="margin-right: 10px"
          >
            添加专业
          </ElButton>
          <ElButton
              type="primary"
              size="small"
              @click="openEditMajorsDialog(scope.row)"
              :icon="Edit"
          >
            编辑学院信息
          </ElButton>
          <ElButton
              type="danger"
              size="small"
              @click="deleteAcademy(scope.row.id, scope.row.academyName)"
              :icon="Delete"
          >
            删除学院
          </ElButton>
        </template>
      </ElTableColumn>
    </ElTable>

    <div class="pagination-container">
      <ElPagination
          :current-page="pagination.currentPage"
          :page-size="pagination.pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑弹窗 -->
    <ElDialog
        v-model="dialogVisible"
        title="关联专业到学院"
        width="500px"
        :before-close="() => { dialogVisible.value = false }"
    >
      <div class="dialog-content" v-loading="dialogLoading">
        <div class="form-item">
          <label class="form-label">学院名称：</label>
          <span>{{ academyData.find(item => item.id === selectedAcademyId)?.academyName }}</span>
        </div>
        <div class="form-item">
          <label class="form-label">选择专业：</label>
          <ElSelect v-model="selectedMajorId" placeholder="请选择专业" style="width: 200px;">
            <ElOption
                v-for="major in majorList"
                :key="major.id"
                :label="major.majorName"
                :value="major.id"
            />
          </ElSelect>
        </div>
      </div>
      <template #footer>
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="submitJoin">确定</ElButton>
      </template>
    </ElDialog>

    <!-- 新增学院弹窗 -->
    <ElDialog
        v-model="addDialogVisible"
        title="新增学院"
        width="400px"
        :before-close="() => { addDialogVisible.value = false }"
    >
      <ElForm ref="addFormRef" :model="addForm.model" :rules="addForm.rules" label-width="80px" v-loading="addDialogLoading">
        <ElFormItem label="学院名称" prop="academyName">
          <ElInput v-model="addForm.model.academyName" placeholder="请输入学院名称" />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="addDialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="submitAddAcademy">确定</ElButton>
      </template>
    </ElDialog>
    <!-- 编辑学院专业弹窗 -->
    <ElDialog
        v-model="editDialogVisible"
        :title="`编辑学院专业 - ${editingAcademy?.academyName}`"
        width="600px"
        :before-close="() => { editDialogVisible.value = false }"
    >
      <div class="dialog-content" v-loading="editDialogLoading">
        <div v-if="academyMajors.length === 0" style="text-align: center; padding: 40px;">
          暂无关联专业
        </div>
        <ElTable
            v-else
            :data="academyMajors"
            style="width: 100%"
            size="small"
        >
          <ElTableColumn prop="majorName" label="专业名称" width="200" />
          <ElTableColumn label="操作" width="100" fixed="right">
            <template #default="scope">
              <ElButton
                  type="danger"
                  size="small"
                  @click="deleteMajor(scope.row.id)"
                  :icon="Delete"
              >
                删除
              </ElButton>
            </template>
          </ElTableColumn>
        </ElTable>
      </div>
      <template #footer>
        <ElButton @click="editDialogVisible = false">关闭</ElButton>
      </template>
    </ElDialog>
  </div>
</template>

<style scoped>
.college-container {
  padding: 20px;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
  margin-right: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-content {
  padding: 20px 0;
}

.form-item {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.form-label {
  width: 100px;
  text-align: right;
  margin-right: 20px;
}
</style>